/**
 * Ai 视频
 */

import { Context, EggApplication, Service } from "egg";

import * as OpenapiClient from '@alicloud/openapi-client'
import type VideoenhanClient from '@alicloud/videoenhan20200320'
import * as Client from '@alicloud/videoenhan20200320'

import * as TeaUtil from '@alicloud/tea-util'
import * as https from 'https'
import * as http from 'http'



export type Resource = {
  type: string
  fileUrl: string
  fileName: string
}

export type RuntimeOpt = {
  [p: string]: any
}
export type VideoOption = {
  fileList: Resource[]
  runtimeOpt: RuntimeOpt
}

const getResponse = function (httpClient, url) {
  return new Promise((resolve, reject) => {
    httpClient.get(url, function (response) {
      resolve(response);
    })
  })
}


export default class AiVideoService extends Service {

  private client: VideoenhanClient
  constructor(ctx) {
    super(ctx)
    const config = new OpenapiClient.Config({
      accessKeyId: this.config.alicloud.AccessKey,
      accessKeySecret: this.config.alicloud.Secret
    })
    config.endpoint = `videoenhan.cn-shanghai.aliyuncs.com`;
    this.client = new Client.default(config)
  }

  async createVideos(opt: VideoOption) {

    try {

      const fileList: Array<any> = []
      for (const f of opt.fileList) {
        // @ts-ignore
        const url = new URL(f.fileUrl)
        const httpClient = (url.protocol == "https:") ? https : http;
        const fsx = new Client.GenerateVideoAdvanceRequestFileList();
        // @ts-ignore
        fsx.fileUrlObject = await getResponse(httpClient, url)
        fsx.type = f.type
        fsx.fileName = f.fileName
        fileList.push(fsx)
      }
      const generateVideoRequest = new Client.GenerateVideoAdvanceRequest({
        fileList
      })

      const runtime = new TeaUtil.RuntimeOptions(opt.runtimeOpt);
      const data = this.client.generateVideoAdvance(generateVideoRequest, runtime)
      return data


    } catch (err) {
      this.logger.error(err)
      throw new Error('生成视频失败')
    }
  }

  async queryResult(taskId: string) {

    const getAsyncJobResultRequest = new Client.GetAsyncJobResultRequest({
      jobId: taskId
    })
    const runtime = new TeaUtil.RuntimeOptions({})

    const result = await this.client.getAsyncJobResultWithOptions(getAsyncJobResultRequest, runtime)
    return result
  }
}